package com.sram.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.apache.commons.io.IOUtils;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageUtil {
	/**
	 * 压缩系数常量：长宽尺寸以100px为基准
	 */
	private static final int DIMISION = 100;
	/**
	 * 压缩系数常量：长宽尺寸以160px为基准
	 */
	private static final int DIMISIONM = 160;
	
	/**
	 * @title 添加图片时自动等比压缩缩略图
	 * @describe 压缩后尺寸大概为100px左右
	 */
	public static Integer[] generateSmallImg(String imgSource, String imgTarget) {
		try {
			File srcfile = new File(imgSource);
			if (!srcfile.exists()) {
				return new Integer[] { 0, 0 };
			}
			Image src = ImageIO.read(srcfile);
			int imgWidth = src.getWidth(null);
			int imgHeight = src.getHeight(null);
			// 1、得到合适的压缩大小，按比例。
			if (imgWidth >= imgHeight) {
				// 1.1、如果是宽图
				imgHeight = Math.round(imgHeight * DIMISION / imgWidth);
				imgWidth = DIMISION;
			} else {
				// 1.2、如果是长图
				imgWidth = Math.round(imgWidth * DIMISION / imgHeight);
				imgHeight = DIMISION;
			}
			// 计算压缩后大小
			int newWidth = imgWidth;
			int newHeight = imgHeight;
			generateImg(imgSource, imgTarget, newWidth, newHeight);
			return new Integer[] { newWidth, newHeight };
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return new Integer[] { 0, 0 };
	}
	
	/**
	 * @title 添加图片时自动等比压缩缩略图
	 * @describe 压缩后尺寸大概为100px左右
	 */
	public static Integer[] generateSmallImgM(String imgSource, String imgTarget) {
		try {
			File srcfile = new File(imgSource);
			if (!srcfile.exists()) {
				return new Integer[] { 0, 0 };
			}
			Image src = ImageIO.read(srcfile);
			int imgWidth = src.getWidth(null);
			int imgHeight = src.getHeight(null);
			// 1、得到合适的压缩大小，按比例。
			if (imgWidth >= imgHeight) {
				// 1.1、如果是宽图
				imgHeight = Math.round(imgHeight * DIMISIONM / imgWidth);
				imgWidth = DIMISIONM;
			} else {
				// 1.2、如果是长图
				imgWidth = Math.round(imgWidth * DIMISIONM / imgHeight);
				imgHeight = DIMISIONM;
			}
			// 计算压缩后大小
			int newWidth = imgWidth;
			int newHeight = imgHeight;
			generateImg(imgSource, imgTarget, newWidth, newHeight);
			return new Integer[] { newWidth, newHeight };
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return new Integer[] { 0, 0 };
	}
	
	/**
	 * @title 指定尺寸压缩图片
	 */
	private static void generateImg(String imgSource, String imgTarget, int widthdist, int heightdist) {
		try {
			File srcfile = new File(imgSource);
			Image src = ImageIO.read(srcfile);
			BufferedImage tag = new BufferedImage(widthdist, heightdist, BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
			FileOutputStream out = new FileOutputStream(imgTarget);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(tag);
			out.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/** 
	  * byte数组转换成16进制字符串 
	  * @param src 
	  * @return 
	  */  
	 public static String bytesToHexString(byte[] src){      
	        StringBuilder stringBuilder = new StringBuilder();      
	        if (src == null || src.length <= 0) {      
	            return null;      
	        }      
	        for (int i = 0; i < src.length; i++) {      
	            int v = src[i] & 0xFF;      
	            String hv = Integer.toHexString(v);      
	            if (hv.length() < 2) {      
	                stringBuilder.append(0);      
	            }      
	            stringBuilder.append(hv);      
	        }      
	        return stringBuilder.toString();      
	    }
	
	 /** 
	  * 根据文件流读取图片文件真实类型 
	  * @param is 
	  * @return 
	  */  
	 public static String getTypeByStream(File file){  
		 FileInputStream is = null;
		 String type = null;
		try {
			is = new FileInputStream(file);
			 byte[] b = new byte[4];   
		    is.read(b, 0, b.length);  
	        type = bytesToHexString(b).toUpperCase();  
	        if(type.startsWith("FFD8FF")){  
	         return "jpg";  
	        }else if(type.startsWith("89504E47")){  
	         return "png";  
	        }else if(type.startsWith("47494638")){  
	         return "gif";  
	        }else if(type.startsWith("49492A00")){  
	         return "tif";  
	        }else if(type.startsWith("424D")){  
	         return "bmp";  
	        }  
		} catch (Exception e1) {
			e1.printStackTrace();
		}finally{
			IOUtils.closeQuietly(is);
		}
		
		return type;
	 }
	 
	 /**
	     * 给图片添加水印
	     * @param filePath  需要添加水印的图片的路径
	     * @param markContent 水印的文字
	     * @param markContentColor 水印文字的颜色
	     * @param qualNum 图片质量
	     * @param watermark 水印ICON
	     * @return
	     */
	 public static void createMark(String filepath,String watermark,String jpgString)throws Exception{
			File file = new File(filepath);
			ImageIcon icon = new ImageIcon(file.getPath());
			BufferedImage bufferedImage = new BufferedImage(
					icon.getIconWidth(), icon.getIconHeight(),
					BufferedImage.TYPE_INT_RGB);

			Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
			// 图像呈现
			g2d.drawImage(icon.getImage(), 0, 0, null);
			// AlphaComposite 类实现一些基本的 alpha 合成规则，将源色与目标色组合，
			// 在图形和图像中实现混合和透明效果
			AlphaComposite alpha = AlphaComposite.getInstance(
					AlphaComposite.SRC_OVER, 0.5f);
			g2d.setComposite(alpha);
			// 水印颜色
			g2d.setColor(Color.red);
			// 为呈现算法设置首选项(此处为文本抗锯齿提示键)的值
			g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
					RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			if(icon.getIconWidth() >= 1024){
				// 水印字体
				g2d.setFont(new Font("宋体_GB2312", Font.ITALIC, 130));
			}else if(icon.getIconWidth() >= 512){
				g2d.setFont(new Font("宋体_GB2312", Font.ITALIC, 40));
			}else{
				g2d.setFont(new Font("宋体_GB2312", Font.ITALIC, 20));
			}
			// 文本呈现
			g2d.drawString(watermark, (icon.getIconWidth()/5),
					(icon.getIconHeight()/2));
			g2d.dispose();
			File fileout = new File(filepath);
			// 生成图片
			ImageIO.write(bufferedImage, jpgString, fileout);
	 }
}
